﻿
using AbstructFactory;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using XF.Common.Redis;
using XF.Meeting.Entity.CommonEntity;
using XF.Meeting.Entity.Query;
using XF.Meeting.Entity.View;

namespace XF.Common.WeChat
{
    public class WeChatHelper
    {
        //ISettingDal settingDal = DalFactory.DalFactory.GetSettingDaL();
        private static readonly string corpid = Convert.ToString(System.Configuration.ConfigurationManager.AppSettings["corpid"]);
        private static readonly string secret = Convert.ToString(System.Configuration.ConfigurationManager.AppSettings["wxsecret"]);
        private HttpClientHelper requst = new HttpClientHelper();
        public AbsFactoryTE abs = (AbsFactoryTE)AbsFactory.CreateInterface();

        private string ACCESS_TOKEN { get; set; }
        /// <summary>
        /// 初始化
        /// </summary>
        /// <param name="corpid">企业id</param>
        /// <param name="secret">应用secret</param>
        public WeChatHelper(string corpid,string secret) {
            ACCESS_TOKEN = GetAccessToken(corpid, secret);
        }
        public WeChatHelper()
        {
            ACCESS_TOKEN = GetAccessToken(corpid, secret);
        }
        public void SendTextMessage(Message message)
        {
            message.agentid= Convert.ToInt32(System.Configuration.ConfigurationManager.AppSettings["agentid"]);
            var response = requst.Post($"https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token={ACCESS_TOKEN}", JsonConvert.SerializeObject(message));
        }
        public string GetAccessToken(string corpid, string secret)
        {
           
            var response = requst.Get($"https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid={corpid}&corpsecret={secret}");
            // Response.Write(response);
            var aaa = Newtonsoft.Json.JsonConvert.DeserializeObject<Root>(response);
            return aaa.access_token;
        }
        public string GetUserId(string Code)
        {
            
            var response = requst.Get($"https://qyapi.weixin.qq.com/cgi-bin/user/getuserinfo?access_token={ACCESS_TOKEN}&code={Code}");
            var aaa = Newtonsoft.Json.JsonConvert.DeserializeObject<Root>(response);
            return aaa.UserId;
        }
        public string GetUserInfo(string UserId)
        {
        
            var response = requst.Get($"https://qyapi.weixin.qq.com/cgi-bin/user/get?access_token={ACCESS_TOKEN}&userid={UserId}");
            //  var aaa = Newtonsoft.Json.JsonConvert.DeserializeObject<Root>(response);
            return response;
        }
        public string CreateChatId(WeChat_Chat enity)
        {
          

            var response = requst.Post($"https://qyapi.weixin.qq.com/cgi-bin/appchat/create?access_token={ACCESS_TOKEN}", JsonConvert.SerializeObject(new CreateChat
            ()
            {
                name = enity.name,
                owner = enity.owner,
                userlist = enity.userList,
                chatid =enity.chatid
            }));
     
            return enity.chatid;
        }

        public string SendMessageForGroup(WeChat_Chat_Msg entity)
        {
            var response = requst.Post($"https://qyapi.weixin.qq.com/cgi-bin/appchat/send?access_token={ACCESS_TOKEN}", JsonConvert.SerializeObject(new ChatInfo()
            {
                chatid = entity.ChatId,
                msgtype = entity.MsgType,
                safe = 0,
                text = new Text(entity.Msg)
            }
          ));
            return response;
        }
        /// <summary>
        /// 获取部门信息，
        /// </summary>
        /// <param name="id">为0查询全部</param>
        /// <returns></returns>
        public  Task<Departments> GetDepartments(int id = 0)
        {
            var response =  requst.Get($"https://qyapi.weixin.qq.com/cgi-bin/department/list?access_token={ACCESS_TOKEN}&id={id}");
            var depList = JsonConvert.DeserializeObject<Departments>(response);
            return Task.FromResult(depList);
        }
        public  Task<userList> GetUserList(int minId, int fetch_child)
        {
            var response =  requst.Get($"https://qyapi.weixin.qq.com/cgi-bin/user/list?access_token={ACCESS_TOKEN}&department_id={minId}&fetch_child={fetch_child}");
            var list = JsonConvert.DeserializeObject<userList>(response);
            return Task.FromResult(list);
        }
        public  void SendWxMssage(CRoomPadQuery query, bool isTen = false)
        {
            var ID = query.CInfoId;

            // if (!dal.IsSendWX(ID,out string error))
            //{

            var dal = abs.CreateConferenceRoomInterface("pad", "");
           // var res = dal.GetCInfoByID(ID).Result;

            //var list = TableToList.ToList<MeetingInfoSingle>(res);
            //var meetingInfoSingle = list[0];
            //meetingInfoSingle.date = Convert.ToDateTime(meetingInfoSingle.BeginTime).ToString("yyyy-MM-dd");
            //meetingInfoSingle.Begin = Convert.ToDateTime(meetingInfoSingle.BeginTime).ToString("HH:mm");
            //meetingInfoSingle.End = Convert.ToDateTime(meetingInfoSingle.EndTime).ToString("HH:mm");
            //meetingInfoSingle.CRooms = meetingInfoSingle.CRoom + "," + meetingInfoSingle.CRooms;
            //var msgList = dal.getMeetInfoAndUserPhone(ID, out string StrError);
            //var phoneList = TableToList.ToList<meetIdS>(msgList.Tables[0]);
            //var phone = phoneList.Select(i => i.Phone).ToList();
            //var userr = GetUserString(phone);
            //var wx = new WeChatHelper();
            //var msg = new Message(new XF.Common.WeChat.Text($"请您参加于{meetingInfoSingle.date}，{meetingInfoSingle.Begin}到{meetingInfoSingle.End}，在（{meetingInfoSingle.CRooms}）举行的由（{meetingInfoSingle.HostPersonName}）主持的（{meetingInfoSingle.ConferenceTheme})主题会议，望准时参加!"), userr);
            //wx.SendTextMessage(msg);
            //if (isTen)
            //{
            //    dal.updateWxState(ID, out string strError);
            //}
            //}

        }
        /// <summary>
        /// 发送会议室视频密码
        /// </summary>
        /// <param name="cinfoId">会议id</param>
        /// <param name="isSign">签到之后，密码生效，预约成功只发送密码</param>
        public void SendTPwdToCreator(CRoomPadQuery query, bool isSign)

        {
            var dal = abs.CreateConferenceRoomInterface("pad", "");
                var res = dal.GetCInfoPwdByID(query.CInfoId).Result;
                var list = TableToList.ToList<MeetRoomPwd>(res);
            if (list.Count==0)
            {
                return;
            }
                var meetingInfoSingle = list[0];
            StringBuilder sb = new StringBuilder();
            foreach (var item in list)
            {
                sb.Append(item.ConferenceName).Append("视频会议室呼入号为").Append(item.TerminalShort).Append("，进入PIN码为").Append(item.PWD).Append("。");
            }
                var wx = new WeChatHelper();
          
            if (isSign)
            {
                try
                {
                    //签到之后修改密码
                  
                    CMSHttpHelper HTTP = new CMSHttpHelper();
                    HTTP.SendPasscode(query.CInfoId);
                    var msg = new Message(new XF.Common.WeChat.Text($"您预定的《{meetingInfoSingle.ConferenceTheme}》主题会议已签到，视频PIN已生效。{sb}如需呼入其他视频会议室，请联系会议协调人获取PIN码。"), list[0].Account);
                    wx.SendTextMessage(msg);
                }
                catch (Exception)
                {

                    throw;
                }
            
            }
            else
            {
                var msg = new Message(new Text($"您预定的《{meetingInfoSingle.ConferenceTheme}》主题会议，PIN码已生成，{sb}如需呼入其他视频会议室，请联系会议协调人获取PIN码。"), list[0].Account);
                wx.SendTextMessage(msg);
            }





        }

        public static string GetUserString(List<string> phone)
        {
            StringBuilder sb = new StringBuilder();

            foreach (var item in phone)
            {
                if (string.IsNullOrWhiteSpace(RedisCache.Hash_Get<string>("UserPhone", item)))
                {
                    continue;
                }

                sb.Append(RedisCache.Hash_Get<string>("UserPhone", item));
                sb.Append("|");
            }
            sb.Remove(sb.Length - 1, 1);
            return sb.ToString();
        }

  
    }
    public class meetIdS
    {
        public int ID { get; set; }
        public string Phone { get; set; }
                public string Account { get; set; }
    }
}

